package com.xiaoxiaoniu.airoleplay.exception;

import com.xiaoxiaoniu.airoleplay.model.ChatResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import jakarta.servlet.http.HttpServletRequest;
import java.util.stream.Collectors;

@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    // 前端开发服务器路由，不需要记录错误
    private static final String[] FRONTEND_PATHS = {
            "/@vite/client", "/@react-refresh", "/src/", "/node_modules/",
            "/vite.svg", "/src/main.js", "/src/App.vue"
    };

    private boolean isFrontendPath(String requestURI) {
        if (requestURI == null) return false;
        for (String path : FRONTEND_PATHS) {
            if (requestURI.contains(path)) {
                return true;
            }
        }
        return false;
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public ResponseEntity<ChatResponse> handleNoHandlerFoundException(
            NoHandlerFoundException ex, HttpServletRequest request) {

        String requestURI = request.getRequestURI();

        // 如果是前端路由，静默处理，不记录错误
        if (isFrontendPath(requestURI)) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(new ChatResponse(false, "前端资源请访问 http://localhost:5173"));
        }

        // 对于其他404，正常记录日志
        logger.warn("接口不存在: {}", requestURI);
        ChatResponse errorResponse = new ChatResponse(false,
                "接口不存在: " + requestURI + "，请检查请求路径");
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(errorResponse);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<ChatResponse> handleGlobalException(Exception ex, HttpServletRequest request) {
        String requestURI = request != null ? request.getRequestURI() : "Unknown URI";

        // 过滤前端路由的异常日志
        if (!isFrontendPath(requestURI)) {
            logger.error("全局异常处理 - 请求路径: {}", requestURI, ex);
        }

        ChatResponse errorResponse = new ChatResponse(false,
                "服务器内部错误: " + (ex.getMessage() != null ? ex.getMessage() : "未知错误"));
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ChatResponse> handleValidationException(MethodArgumentNotValidException ex) {
        String errorMessage = ex.getBindingResult()
                .getFieldErrors()
                .stream()
                .map(error -> error.getField() + ": " + error.getDefaultMessage())
                .collect(Collectors.joining("; "));

        ChatResponse errorResponse = new ChatResponse(false, "请求参数验证失败: " + errorMessage);
        return ResponseEntity.badRequest().body(errorResponse);
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<ChatResponse> handleIllegalArgumentException(IllegalArgumentException ex) {
        logger.warn("参数错误: {}", ex.getMessage());
        ChatResponse errorResponse = new ChatResponse(false, "请求参数错误: " + ex.getMessage());
        return ResponseEntity.badRequest().body(errorResponse);
    }

    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<ChatResponse> handleRuntimeException(RuntimeException ex, HttpServletRequest request) {
        String requestURI = request != null ? request.getRequestURI() : "Unknown URI";

        // 过滤前端路由的异常日志
        if (!isFrontendPath(requestURI)) {
            logger.error("运行时异常 - 请求路径: {}", requestURI, ex);
        }

        ChatResponse errorResponse = new ChatResponse(false,
                "系统繁忙，请稍后重试: " + ex.getMessage());
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
    }
}